import 'dart:io';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lmmi/common/index.dart';

class TimeCapsuleDetailPage extends ConsumerStatefulWidget {
  const TimeCapsuleDetailPage({super.key, required this.timeCapsuleId});
  final String timeCapsuleId;

  @override
  ConsumerState<TimeCapsuleDetailPage> createState() =>
      _TimeCapsuleDetailPageState();
}

class _TimeCapsuleDetailPageState extends ConsumerState<TimeCapsuleDetailPage>
    with WidgetsBindingObserver {
  TimeCapsule? _timeCapsule;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _loadTimeCapsule();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台返回前台时，刷新用户状态
    if (state == AppLifecycleState.resumed) {
      ref.read(userProvider.notifier).reloadCurrentUser();
    }
  }

  // 加载时间胶囊详情
  Future<void> _loadTimeCapsule() async {
    try {
      final timeCapsule = await TimeCapsuleService.getTimeCapsuleById(
        widget.timeCapsuleId,
      );
      if (mounted) {
        setState(() {
          _timeCapsule = timeCapsule;
          _isLoading = false;

          debugPrint('timeCapsule: $_timeCapsule');
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to load time capsule: $e')),
        );
      }
    }
  }

  // 检查用户是否可以查看时间胶囊内容
  bool _canViewTimeCapsuleContent() {
    // 使用watch而不是read，确保用户状态变化时UI会重新构建
    final currentUser = ref.watch(currentUserProvider);
    if (currentUser == null) return false;

    // VIP用户可以查看所有内容
    if (currentUser.isVip) return true;

    // 非VIP用户不能查看已发送的时间胶囊内容
    return false;
  }

  // 显示VIP提示弹窗
  void _showVipRequiredDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('VIP Required'),
        content: Text(
          'Only VIP users can view sent time capsules. Upgrade to VIP to unlock this feature!',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 跳转到订阅页面
              AppRouterExtension(context).navigateTo(AppRoutes.subscribe);
            },
            child: Text('Upgrade'),
          ),
        ],
      ),
    );
  }

  // 获取完整图片路径
  Future<String?> _getFullImagePath(String imagePath) async {
    // 兼容旧数据：绝对路径直接返回
    if (imagePath.startsWith('/')) {
      return imagePath;
    }
    // Asset 路径：以 assets/ 开头的是 Asset 资源
    if (imagePath.startsWith('assets/')) {
      return imagePath; // Asset 路径直接返回，用于 Image.asset()
    }
    // 新数据：动态构建完整路径
    return await ImagePickerUtil.getFullImagePath(imagePath);
  }

  // 判断是否为 Asset 图片
  bool _isAssetImage(String imagePath) {
    return imagePath.startsWith('assets/');
  }

  // 构建图片组件
  Widget _buildImageWidget(String imagePath) {
    // Asset 图片：直接使用 Image.asset
    if (_isAssetImage(imagePath)) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8.r),
        child: Image.asset(
          imagePath,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return _buildErrorPlaceholder();
          },
        ),
      );
    }

    // 本地文件图片：使用 FutureBuilder 异步加载
    return FutureBuilder<String?>(
      future: _getFullImagePath(imagePath),
      builder: (context, snapshot) {
        if (snapshot.hasData && snapshot.data != null) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(8.r),
            child: Image.file(
              File(snapshot.data!),
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return _buildErrorPlaceholder();
              },
            ),
          );
        } else {
          // 加载中时显示占位符
          return _buildLoadingPlaceholder();
        }
      },
    );
  }

  // 构建错误占位符
  Widget _buildErrorPlaceholder() {
    return Container(
      color: Colors.grey.withValues(alpha: 0.3),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, color: Colors.grey, size: 32.sp),
            SizedBox(height: 8.h),
            Text(
              'Image not found',
              style: TextStyle(color: Colors.grey, fontSize: 12.sp),
            ),
          ],
        ),
      ),
    );
  }

  // 构建加载占位符
  Widget _buildLoadingPlaceholder() {
    return Container(
      color: Colors.grey.withValues(alpha: 0.1),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: 24.w,
              height: 24.w,
              child: CircularProgressIndicator(
                strokeWidth: 2.w,
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF7700)),
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              'Loading image...',
              style: TextStyle(color: Color(0xFFFF7700), fontSize: 12.sp),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text(
            'Time Capsule Detail',
            style: TextStyle(
              color: Colors.black,
              fontSize: 24.sp,
              fontFamily: 'Port',
              fontWeight: FontWeight.w400,
              height: 0.83,
            ),
          ),
          backgroundColor: Colors.transparent,
          elevation: 0,
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios_new_rounded,
              color: Colors.black,
              size: 22.sp,
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ),
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(MyImages.timeCapsuleBg),
              fit: BoxFit.fill,
            ),
          ),
          child: Center(
            child: CircularProgressIndicator(color: Color(0xFFFF7700)),
          ),
        ),
      );
    }

    if (_timeCapsule == null) {
      return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text(
            'Time Capsule Detail',
            style: TextStyle(
              color: Colors.black,
              fontSize: 24.sp,
              fontFamily: 'Port',
              fontWeight: FontWeight.w400,
              height: 0.83,
            ),
          ),
          backgroundColor: Colors.transparent,
          elevation: 0,
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios_new_rounded,
              color: Colors.black,
              size: 22.sp,
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ),
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(MyImages.timeCapsuleBg),
              fit: BoxFit.fill,
            ),
          ),
          child: Center(
            child: Text(
              'Time capsule not found',
              style: TextStyle(
                color: Colors.black,
                fontSize: 18.sp,
                fontFamily: 'ReenieBeanie',
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      );
    }

    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text(
          'Time Capsule Detail',
          style: TextStyle(
            color: Colors.black,
            fontSize: 24.sp,
            fontFamily: 'Port',
            fontWeight: FontWeight.w400,
            height: 0.83,
          ),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios_new_rounded,
            color: Colors.black,
            size: 22.sp,
          ),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.timeCapsuleBg),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: Stack(
            children: [
              Positioned(
                left: 13.w,
                top: 108.h,
                right: 14.w,
                bottom: 35.h,
                child: Container(
                  width: 348.w,
                  height: 669.h,
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                      side: BorderSide(
                        width: 1,
                        color: const Color(0xFFFF7700),
                      ),
                    ),
                  ),
                  child: _canViewTimeCapsuleContent()
                      ? Column(
                          children: [
                            // 文字显示区域
                            Expanded(
                              flex: _timeCapsule!.imagePath != null ? 1 : 2,
                              child: Container(
                                width: double.infinity,
                                padding: EdgeInsets.all(16),
                                child: SingleChildScrollView(
                                  child: Text(
                                    _timeCapsule!.content,
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 20.sp,
                                      fontFamily: 'ReenieBeanie',
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            // 图片显示区域 - 只在有图片时显示
                            if (_timeCapsule!.imagePath != null)
                              Expanded(
                                flex: 1,
                                child: Container(
                                  width: double.infinity,
                                  margin: EdgeInsets.all(16.w),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8.r),
                                    border: Border.all(
                                      color: const Color(0xFFFF7700),
                                      width: 1.w,
                                    ),
                                  ),
                                  child: _buildImageWidget(
                                    _timeCapsule!.imagePath!,
                                  ),
                                ),
                              ),
                          ],
                        )
                      : Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.lock_outline,
                                size: 64.sp,
                                color: Colors.grey,
                              ),
                              SizedBox(height: 16.h),
                              Text(
                                'VIP Required',
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 24.sp,
                                  fontFamily: 'ReenieBeanie',
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              SizedBox(height: 8.h),
                              Text(
                                'Only VIP users can view\nsent time capsules',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  color: Colors.grey,
                                  fontSize: 16.sp,
                                  fontFamily: 'ReenieBeanie',
                                  fontWeight: FontWeight.w400,
                                ),
                              ),
                              SizedBox(height: 24.h),
                              ElevatedButton(
                                onPressed: _showVipRequiredDialog,
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Color(0xFFFF7700),
                                  foregroundColor: Colors.white,
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 24.w,
                                    vertical: 12.h,
                                  ),
                                ),
                                child: Text(
                                  'Upgrade to VIP',
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
